# -*- coding: utf-8 -*-

import sys, os
import getopt, glob

def copy_bfile(name, pref="c_"):
    with open(name, "rb") as f:
        try:
            p, n = os.path.split(name)
            nf = open(os.path.join(p, pref+n), "wb")
            nf.write(f.read())
        except Exception, e:
            print e

def copy_rbfile(name, dstname):
    with open(name, "rb") as f:
        try:
            nf = open(dstname, "wb")
            nf.write(f.read())
        except Exception, e:
            print e

def pjoin(*args):
    ret = ""
    for p in args:
        if isinstance(p, str) and p != "":
            ret += p.strip()
            if (ret[-1] != '/'):
                ret += '/'
    if (ret != "" and ret[-1] == '/'):
        ret = ret[0:-1]
    return ret

def copy_dir(dirpath, top="c_"):
    ret = os.walk(dirpath)
    p, n = os.path.split(dirpath)
    dstroot = os.path.join(p, top+n)
    while os.path.exists(dstroot): 
        dstroot = dstroot+'1'
    os.makedirs(dstroot)

    for root, dirs, files in ret:
        #print root
        for sfile in files:
            fpath = pjoin(root, sfile)
            rpath = os.path.relpath(fpath, dirpath)
            print "[F]", root, sfile, '[R]', rpath
            copy_rbfile(fpath, os.path.join(dstroot, rpath))
        for sdir in dirs:
            fpath = pjoin(root, sdir)
            rpath = os.path.relpath(fpath, dirpath)
            print "[D]", root, sdir, dstroot
            os.makedirs(pjoin(dstroot, rpath))

def usage():
    print """\
    ncp <file1> <file_string>    to change files
    ncp -d <dir1>"""

if __name__ == "__main__":
    opts, args = getopt.getopt(
        sys.argv[1:],
        "d",
        ['help',]
    )

    if len(args) == 0:
        usage()
        sys.exit(-2)

    for o, a in opts:
        if o in ('-d'):
            copy_dir(args[0])
            sys.exit(1)
        elif o in ('--help'):
            usage()
            sys.exit(2)

    for f in args:
        fl = glob.glob(f)
        for sf in fl:
            print "[F]", sf
            copy_bfile(sf)
